<?php

namespace Kateba\TTICOBundle\Entity;

use Symfony\Component\Validator\Constraints as Assert;
use Doctrine\ORM\Mapping as ORM;

/**
 * Kateba\GOOBundle\Entity\Post
 *
 * @ORM\Table(name="Post")
 * @ORM\HasLifecycleCallbacks
 * @ORM\Entity(repositoryClass="Kateba\TTICOBundle\Entity\PostRepository")
 */
class Post {

    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $postType
     *
     * @ORM\Column(name="postType", type="string", length=255)
     */
    private $postType;

    /**
     * @var string $title
     *
     * @ORM\Column(name="title", type="string", length=255)
     */
    private $title;

    /**
     * @var text $content
     *
     * @ORM\Column(name="content", type="text")
     */
    private $content;

    /**
     * @var date $createdAt
     *
     * @ORM\Column(name="created_at", type="date")
     */
    private $createdAt;

    /**
     * @var string $uploadedFile
     *
     * @ORM\Column(name="uploadedFile", type="string", length=20, nullable=true)
     */
    private $uploadedFile;

    /**
     * a temp variable for storing the old file name to delete the old file after the update
     * @var string $temp
     */
    private $fileTemp;

    /**
     * @var \Symfony\Component\HttpFoundation\File\UploadedFile
     */
    public $document;

    /**
     * @var string $image
     *
     * @ORM\Column(name="image", type="string", length=20, nullable=true)
     */
    private $image;

    /**
     * a temp variable for storing the old image name to delete the old image after the update
     * @var string $temp
     */
    private $temp;

    /**
     * this flag is for detecting if the image has been handled
     * @var boolean $imageHandeled
     */
    private $imageHandeled = FALSE;

    /**
     * @Assert\Image
     * @var \Symfony\Component\HttpFoundation\File\UploadedFile
     */
    public $file;

    /**
     * Set image
     *
     * @param string $image
     */
    public function setImage($image) {
        $this->image = $image;
    }

    /**
     * Get image
     *
     * @return string 
     */
    public function getImage() {
        return $this->image;
    }

    /**
     * @ORM\PrePersist()
     * @ORM\PreUpdate()
     */
    public function preUpload() {
        if ((NULL !== $this->file || NULL !== $this->document) && !$this->imageHandeled) {
            //get the upload directory
            $uploadDir = $this->getUploadRootDir();
            //check if the upload directory exists
            if (!@is_dir($uploadDir)) {
                //get the old umask
                $oldumask = umask(0);
                //not a directory probably the first time for this category try to create the directory
                $success = @mkdir($uploadDir, 0755, TRUE);
                //reset the umask
                umask($oldumask);
                //check if we created the folder
                if (!$success) {
                    //could not create the folder throw an exception to stop the insert
                    throw new \Exception("Can not create the image directory $uploadDir");
                }
            }
            //check if we will upload an image
            if ($this->file) {
                //get the image extension
                $extension = $this->file->guessExtension();
                //generate a random image name
                $img = uniqid();
                //check that the file name does not exist
                while (@file_exists("$uploadDir/$img.$extension")) {
                    //try to find a new unique name
                    $img = uniqid();
                }
                //check if we have an old image
                if ($this->image) {
                    //store the old name to delete the image on the upadate
                    $this->temp = $this->image;
                }
                //set the image new name
                $this->image = "$img.$extension";
            }
            //check if we will upload a file
            if ($this->document) {
                //get the file extension
                $fileExtension = $this->document->guessExtension();
                //generate a random file name
                $fileName = uniqid();
                //check that the file name does not exist
                while (@file_exists("$uploadDir/$fileName.$fileExtension")) {
                    //try to find a new unique name
                    $fileName = uniqid();
                }
                //check if we have an old file
                if ($this->uploadedFile) {
                    //store the old name to delete the file on the upadate
                    $this->fileTemp = $this->uploadedFile;
                }
                //set the file new name
                $this->uploadedFile = "$fileName.$fileExtension";
            }
            //set the flag to indecate that the image has been handled
            $this->imageHandeled = TRUE;
        }
    }

    /**
     * @ORM\PostPersist()
     * @ORM\PostUpdate()
     */
    public function upload() {
        if (NULL !== $this->file) {
            // you must throw an exception here if the file cannot be moved
            // so that the entity is not persisted to the database
            // which the UploadedFile move() method does
            $this->file->move($this->getUploadRootDir(), $this->image);
            //remove the file as you do not need it any more
            $this->file = NULL;
            //check if we have an old image
            if ($this->temp) {
                //try to delete the old image
                @unlink($this->getUploadRootDir() . '/' . $this->temp);
            }
        }
        if (NULL !== $this->document) {
            // you must throw an exception here if the file cannot be moved
            // so that the entity is not persisted to the database
            // which the UploadedFile move() method does
            $this->document->move($this->getUploadRootDir(), $this->uploadedFile);
            //remove the file as you do not need it any more
            $this->document = NULL;
            //check if we have an old image
            if ($this->fileTemp) {
                //try to delete the old image
                @unlink($this->getUploadRootDir() . '/' . $this->fileTemp);
            }
        }
    }

    /**
     * @ORM\PostRemove()
     */
    public function postRemove() {
        //check if we have an image
        if ($this->image) {
            //try to delete the image
            @unlink($this->getImageAbsolutePath());
        }
        //check if we have a document
        if ($this->uploadedFile) {
            //try to delete the file
            @unlink($this->getFileAbsolutePath());
        }
    }

    /**
     * @return string the path of image starting of root
     */
    public function getFileAbsolutePath() {
        return $this->getUploadRootDir() . '/' . $this->uploadedFile;
    }

    /**
     * @return string the path of image starting of root
     */
    public function getImageAbsolutePath() {
        return $this->getUploadRootDir() . '/' . $this->image;
    }

    /**
     * @return string the relative path of image starting from web directory 
     */
    public function getWebPath() {
        return NULL === $this->image ? NULL : '/' . $this->getUploadDir() . '/' . $this->image;
    }

    /**
     * @return string the relative path of file starting from web directory 
     */
    public function getFileWebPath() {
        return NULL === $this->uploadedFile ? NULL : '/' . $this->getUploadDir() . '/' . $this->uploadedFile;
    }

    /**
     * @return string the path of upload directory starting of root
     */
    public function getUploadRootDir() {
        // the absolute directory path where uploaded documents should be saved
        return __DIR__ . '/../../../../web/' . $this->getUploadDir();
    }

    /**
     * @return string the document upload directory path starting from web folder
     */
    protected function getUploadDir() {
        return 'uploads/post';
    }

    public function __construct() {
        $this->createdAt = new \DateTime();
    }

    public function __toString() {
        return $this->title;
    }

    /**
     * Get id
     *
     * @return integer 
     */
    public function getId() {
        return $this->id;
    }

    /**
     * Set title
     *
     * @param string $title
     */
    public function setTitle($title) {
        $this->title = $title;
    }

    /**
     * Get title
     *
     * @return string 
     */
    public function getTitle() {
        return $this->title;
    }

    /**
     * Set content
     *
     * @param text $content
     */
    public function setContent($content) {
        $this->content = $content;
    }

    /**
     * Get content
     *
     * @return text 
     */
    public function getContent() {
        return $this->content;
    }

    /**
     * Get createdAt
     *
     * @return date 
     */
    public function getCreatedAt() {
        return $this->createdAt;
    }

    /**
     * Set postType
     *
     * @param string $postType
     */
    public function setPostType($postType) {
        $this->postType = $postType;
    }

    /**
     * Get postType
     *
     * @return string 
     */
    public function getPostType() {
        return $this->postType;
    }

    /**
     * Set uploadedFile
     *
     * @param string $uploadedFile
     */
    public function setUploadedFile($uploadedFile) {
        $this->uploadedFile = $uploadedFile;
    }

    /**
     * Get uploadedFile
     *
     * @return string 
     */
    public function getUploadedFile() {
        return $this->uploadedFile;
    }

    /**
     * this function will get the valid post types
     * @return array
     */
    public function getPostTypes() {
        return array(
            'consultation' => 'consultation',
            'meeting' => 'meeting',
            'training' => 'training',
            'Workshop' => 'Workshop',
            'technical_securely_school' => 'technical_securely_school',
            'dual_education' => 'dual_education',
            'employment_unit' => 'employment_unit',
            'courses' => 'courses',
            'news' => 'news',
            'events' => 'events'
        );
    }

}